package com.jiepu.daily.corejava.advanceed.part6thread.tortoiseandrabbitrace2;

import org.jetbrains.annotations.NotNull;

/**
 * @Description: 使用两条线程模拟一只乌龟和一只兔兔赛跑，乌龟每秒跑2~4米，兔兔每秒跑7~9米。
 * 但是兔兔会有30%的可能性睡眠三秒。
 * 要求：采用两种不同的方法计算成绩。
 * -   1、和上述案例相同，允许龟兔全部跑完全程。通过时间来决定名次。
 * -   2、残酷竞赛，只看谁第一个到终点。其中一个到终点之后，另外一个则立即停止跑步。
 * @author: xinjie.txt
 * @date: 2020/7/30  8:07
 */
public class TortoiseAndRabbitRace2 {
	public static final int LENGTH = 100;


	static class TortoiseThread extends Thread {
		long time = 0L;
		int sum = 0;
		long t1 = System.currentTimeMillis();

		@Override
		public void run() {

			while (sum < LENGTH) {
				int metter = (int) (Math.random() * 3 + 2);
				sum += metter;
				System.out.println(getName() + " this turn: " + metter
						+ " Total: " + sum);

				try {
					Thread.sleep(100);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}

			} // while


			long t2 = System.currentTimeMillis();
			time = t2 - t1;
			System.out.println(getName() + " Total Time: " + time);
		} // run

		public TortoiseThread(@NotNull String name) {
			super(name);
		}


	}


	static class RabbitThread extends Thread {
		long time = 0L;

		@Override
		public void run() {
			int sum = 0;
			int metter = 0;
			long t1 = System.currentTimeMillis();
			while (sum < LENGTH) {
				if ((int) (Math.random() * 100 + 1) <= 30) {
					System.out.println(getName() + "want sleep !!!");
					// sleep
					try {
						Thread.sleep(3000);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				} else {
					// go go go
					metter = (int) (Math.random() * 3 + 7);
					sum += metter;
					System.out.println(getName() + "This turn: "
							+ metter + "Total Instance: " + sum);
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}

			} // while

			long t2 = System.currentTimeMillis();
			time = t2 - t1;
			System.out.println(getName() + " Time: " + time);
		} // run();

		public RabbitThread(@NotNull String name) {
			super(name);
		}
	}


	public static void main(String[] args) {
		TortoiseThread tortoiseThread = new TortoiseThread("Tortoise");
		RabbitThread rabbitThread = new RabbitThread("Rabbit");

		tortoiseThread.start();
		rabbitThread.start();
		try {
			tortoiseThread.join();
			rabbitThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}


		if (tortoiseThread.time == rabbitThread.time) {
			System.out.println(tortoiseThread.getName() + "===" + rabbitThread.getName());
		} else if (tortoiseThread.time < rabbitThread.time) {
			System.out.println(tortoiseThread.getName() + "win  !!!");
		} else if (rabbitThread.time < tortoiseThread.time) {
			System.out.println(rabbitThread.getName() + "win  !!!");
		}

	} // main


}
